import os
import datetime

def rename_videos_by_modification_time(directory):
    """
    将目录中的视频文件按照其修改时间直接重命名为统一的格式：v_日期_时间
    """
    # 确保目录存在
    if not os.path.exists(directory):
        print(f"目录 {directory} 不存在!")
        return

    # 常见视频文件扩展名
    video_extensions = ['.mp4', '.mov', '.avi', '.mkv', '.wmv', '.flv', '.webm', '.m4v', '.3gp']
    
    # 获取目录中的所有视频文件
    video_files = []
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)
        if os.path.isfile(file_path):
            _, ext = os.path.splitext(filename)
            if ext.lower() in video_extensions:
                video_files.append(filename)
    
    if not video_files:
        print("未找到视频文件!")
        return
        
    print(f"找到 {len(video_files)} 个视频文件")
    renamed_count = 0
    skipped_count = 0
    
    # 先收集所有重命名操作，以检查潜在冲突
    rename_operations = []
    temp_names = []  # 用于存储临时文件名
    
    for filename in video_files:
        file_path = os.path.join(directory, filename)
        
        # 获取文件的修改时间
        mod_time = os.path.getmtime(file_path)
        dt = datetime.datetime.fromtimestamp(mod_time)
        
        # 格式化日期和时间: v_YYYYMMDD_HHMMSS
        date_str = dt.strftime("%Y%m%d")
        time_str = dt.strftime("%H%M%S")
        
        # 获取文件扩展名
        _, ext = os.path.splitext(filename)
        
        # 创建新文件名
        new_filename = f"v_{date_str}_{time_str}{ext}"
        new_path = os.path.join(directory, new_filename)
        
        # 检查是否有同名文件或是否已在计划重命名列表中
        counter = 1
        while (os.path.exists(new_path) and os.path.normpath(new_path) != os.path.normpath(file_path)) or new_filename in temp_names:
            # 如果文件已存在，添加序号
            name_without_ext = f"v_{date_str}_{time_str}_{counter}"
            new_filename = f"{name_without_ext}{ext}"
            new_path = os.path.join(directory, new_filename)
            counter += 1
        
        # 将操作添加到列表中
        rename_operations.append((file_path, new_path))
        temp_names.append(new_filename)
    
    # 先使用临时名称进行重命名，避免文件名冲突
    for i, (old_path, new_path) in enumerate(rename_operations):
        old_filename = os.path.basename(old_path)
        new_filename = os.path.basename(new_path)
        
        # 如果新旧文件名相同，则跳过
        if old_path == new_path:
            print(f"跳过 {old_filename} - 新旧文件名相同")
            skipped_count += 1
            continue
            
        try:
            # 重命名文件
            os.rename(old_path, new_path)
            print(f"已重命名: {old_filename} -> {new_filename}")
            renamed_count += 1
        except Exception as e:
            print(f"重命名 {old_filename} 时出错: {e}")
            skipped_count += 1
    
    print(f"\n完成! 统计信息:")
    print(f"- 成功重命名: {renamed_count} 个文件")
    print(f"- 跳过: {skipped_count} 个文件")


if __name__ == "__main__":
    import sys
    
    if len(sys.argv) > 1:
        directory = sys.argv[1]
    else:
        directory = input("请输入视频文件所在的目录路径: ")
    
    rename_videos_by_modification_time(directory)